class Solution(object):
    def eventualSafeNodes(self, graph):
        """
        :type graph: List[List[int]]
        :rtype: List[int]
        """
        n = len(graph)
        p = [0] * n

        def search(u):
            if p[u] == 1:
                return False
            if p[u] == 2:
                return True
            if not graph[u]:
                p[u] = 2
                return True
            p[u] = 1
            for v in graph[u]:
                if not search(v):
                    return False
            p[u] = 2
            return True

        out = []
        for i in range(n):
            if search(i):
                out.append(i)

        return out


data = Solution()
graph = [[1, 2], [2, 3], [5], [0], [5], [], []]
print(data.eventualSafeNodes(graph))
